<template>
  <div class="departManaIndex">
    <userHeader />
    <div class="breadClum">
      <span>
          <router-link :to="{path:'/pageIndex'}">  <a class="bread1">当前位置：首页  >  </a></router-link>
           <router-link :to="{path:'/systemSetting'}"> <a class="bread2">系统设置  ></a></router-link>
          <a class="bread2">部门管理</a>
      </span>
    </div>
    <div class="navList">
      <span class="sp1" @click.stop="addDepartment">添加部门</span>
            <!--<span @click.stop="editorSelect">-->
                 <!--编辑-->
            <!--</span>-->
            <!--<span @click.stop="delFn">-->
                 <!--删除-->
            <!--</span>-->
    </div>
    <el-table
      :row-class-name="tableRowClassName"
      :data="tableData3"
      stripe
      ref="tableData3"
      class="el-table"
      @selection-change="handleSelectionChange"
      :height="height"
      style="width: 100%">
      <el-table-column
        label=""
        type="selection"
        prop="ID"
        width="70">
      </el-table-column>
      <el-table-column
        prop="company_num"
        :label="company_Item"
        :render-header="renderHeaderOne"
        width="160">
      </el-table-column>
      <el-table-column
        prop="company_name"
        label="公司名称"
        width="246">
      </el-table-column>
      <el-table-column
        prop="section_name"
        label="部门名称"
        width="185">
      </el-table-column>

      <el-table-column
        prop="opt"
        label="操作"
        width="200">
        <template slot-scope="scope">
          <span @click.stop="editor(scope.row.section_id,scope.row.index,scope.row.company_name,scope.row.company_num)" class="e-ditor">编辑</span>
          <span @click.stop="delete1(scope.row.section_id,scope.row.index,scope.row)" class="d-elete" >删除</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="blank"
        label=""
        width="auto">
      </el-table-column>
    </el-table>
    <div class="e-table-footer">
        <div class="e-selectAll">
            <!--<el-checkbox @change="selectAll"></el-checkbox>-->
          <el-checkbox @change="selectAll" v-model="selectAllValue">

          </el-checkbox>
        </div>
      <div class="e-selectText">
          <span>全选</span>
          <span class="e-del" @click.stop="delFn">删除</span>
      </div>
    </div>
    <el-dialog :before-close="handleClose" :title=title :visible.sync="dialogFormVisible">
      <el-form :model="form"  ref="editorForm" :rules="rules">
        <el-form-item label="部门名称" :label-width="formLabelWidth" prop="section_name">
          <el-input v-model="form.section_name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="所属单位" :label-width="formLabelWidth" prop="company_id">
          <el-tree
              :data="data3"
              :props="defaultProps"
              :show-checkbox="true"
              default-expand-all
              :check-on-click-node="true"
              node-key="company_id"
              ref="tree"
              @check="checkTest"
              @check-change="setCheckedKeys"
              @node-click="nodeClick"
              :expand-on-click-node="false"
              :check-strictly=true
              highlight-current
            @current-change="changeCurrent">
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd">取 消</el-button>
        <el-button type="primary" @click="confirmAdd('editorForm')">确 定</el-button>
      </div>
    </el-dialog>
    <deleteAlarm @cancelOpt="cancelOpt" @confirmOpt="confirmOpt" :dialogVisible2="dialogFormVisible2"/>
    <el-pagination
      :page-count=pageSize
      layout="total,prev, pager, next, jumper"
      :current-page.sync="currentPage"
      @current-change="currentChange"
    >
    </el-pagination>
  </div>
</template>
<script>
  import userHeader from '@/components/header.vue'
  import deleteAlarm from '@/components/deleteAlarm.vue'
  import treeToArray from '@/page/test/index.js'
  import {strToHexCharCode,toFixedBit,dec2hex,formatTime,getNewDate } from  '@/utils/index.js';
  import {mapState} from 'vuex'
  export default({
    computed:{
      ...mapState({
        company_Item:state=>state.app.loginState.company_num ||sessionStorage.getItem('company_num'),
        height:state=>sessionStorage.getItem('height')||state.app.height,
      }),
      formatData: function() {
        let tmp;
        console.log('`````````````')
        if (!Array.isArray(this.companyData)) {
          tmp = [this.companyData]
        } else {
          tmp = this.companyData
        }
        const func = this.evalFunc || treeToArray
        const args = this.evalArgs ? Array.concat([tmp, this.expandAll], this.evalArgs) : [tmp, this.expandAll]
        console.log(func.apply(null, args))
        return func.apply(null, args)
      }
    },
    components:{
      userHeader,
      deleteAlarm
    },
    data (){
      var checkSection = (rule, value, callback) => {
        if (value === ''||value==undefined) {
          callback(new Error('请填写部门名称'));
        }
        else {
          callback();
        }
      };
      var checkCompany = (rule, value, callback) => {
//          console.log(this.currentNodeKey)
          console.log(this.checkedId)
          console.log(this.$refs.tree.getCheckedNodes())
        if(this.$refs.tree.getCheckedNodes().length==0){
          return callback(new Error('请选择评价单位'));
        }else{
          callback()
        }
//        if(this.currentNodeKey==undefined||this.currentNodeKey==''){
//          return callback(new Error('请选择评价单位'));
//        }else if(!this.currentNodeKey.company_name){
//          return callback(new Error('请选择评价单位'));
//        }else {
//          callback()
//        }
      };
      return {
        title:'',
        editorFlag:false,
        dialogFormVisible:false,
        dialogFormVisible2:false,
        section_id:'',
        logLevel:'',
        company_id:'',
        company_num:'',
        index:'',
        page:1,
        pageSize:1,
        i:0,
        total:0,
        currentPage:1,
        pageCount:0,
        form: {
          name: '',
          region: '',
          date1: '',
          date2: '',
          delivery: false,
          type: [],
          resource: '',
          desc: ''
        },
        companyList:'',
        formLabelWidth: '120px',
        tableData3: [],
        companyData:[],
        data3:[],
        defaultProps: {
        children: 'son_company',
          label: 'company_name'
      },
        rules: {
          section_name: [
            { required: true,validator:checkSection,trigger: 'blur'}
          ],
          company_id:[
            { required: true,validator:checkCompany,trigger: 'blur'}
          ]
        },
        multipleSelection: [],
        demoData:['11','22','33'],
        selectAllValue:false,
      }
    },
    methods: {
//      selectAll(val){
//        if(val){
//          for(var i in this.tableData3){
//            this.$refs.tableData3.toggleRowSelection(this.tableData3[i]);
//          }
//        }else{
//          this.$refs.tableData3.clearSelection();
//        }
//      },
      //        全选
      selectAll(){
        this.$refs.tableData3.toggleAllSelection();
      },
//      handleSelectionChange(val){
//        this.multipleSelection = val;
//      },
      handleSelectionChange(val){
        console.log(val)
        console.log(val.length != this.tableData3.length);
        if(val.length != this.tableData3.length){
          this.selectAllValue = false;
        }else {
          this.selectAllValue = true
        }
        this.multipleSelection =val;
      },
      handleClose(){
        this.form={}
        this.$refs.tree.setCheckedNodes([]);
        this.dialogFormVisible=false
      },
      checkTest(data,checkNode){
//        console.log(data.company_id)
//        this.form.company_id=data.company_id
//        this.form.company_name=data.company_name
      },
      //树状结构分类
      changeCurrent(data,node,test){
//        console.log(data)
//        console.log(node)
      },
      nodeClick(data,checked,node){
          console.log(123)
        this.checkedId = data.company_id
        this.$refs.tree.setCheckedNodes([data]);
      },
      setCheckedKeys(data,checked,node){
        if(checked == true){
          this.checkedId = data.company_id;
          this.$refs.tree.setCheckedNodes([data]);
        }

//        this.i++;
//        if(this.i%2==0) {
//          if (checked) {
//            this.$refs.tree.setCheckedNodes([]);
//            this.$refs.tree.setCheckedNodes([data]);
//            //交叉点击节点
//          } else {
//            this.currentNodeKey=''
//            this.$refs.tree.setCheckedNodes([]);
//            //点击已经选中的节点，置空
//          }
//        }else{
//          this.currentNodeKey ={
//            company_id:data.company_id,
//            company_name:data.company_name
//          }
//        }
      },
      tableRowClassName ({row, rowIndex}) {
        //把每一行的索引放进row
        row.index = rowIndex;
      },
      addDepartment(){
        this.dialogFormVisible =true
        this.title='添加部门'
        this.form={}
//        this.$refs.tree.setCheckedNodes([]);
      },
      editor(id,index,company_name,company_num){
        this.title='编辑'
        this.section_id=id
        this.index=index
        this.company_name=company_name
        this.company_num=company_num
        this.dialogFormVisible =true
        this.axios.get('/api/v1/system/section/'+`${id}`).then((res)=>{
            if(res.data.code==0){
                this.form =res.data.data
                this.$refs.tree.setCheckedKeys([res.data.data.company_id]);
            }else{
                this.$alert(res.data.message,'提示')
            }
        })
      },
      //分页状态改变
      currentChange(val){
        this.page =val
        this.initData( this.page)
      },
      //表格单行删除
      delete1(id,index,row){
        this.dialogFormVisible2=true
        this.section_id =id;
        this.index =index;
        if(this.multipleSelection.length>=1){
          this.multipleSelection=[];
        }
        this.multipleSelection.push(row);
        console.log(this.multipleSelection)
      },
      //底部删除
      delFn(){
        if(this.multipleSelection.length==0){
          this.$alert('请先选择需要删除的表格','提示')
        }else{
          this.dialogFormVisible2 =true
        }
      },
      editorSelect(){
        if(this.multipleSelection.length==0){
          this.$alert('请先选择需要编辑的表格','提示')
        }else if(this.multipleSelection.length>1){
          this.$alert('一次只可编辑一条数据','提示')
        }else{
           this.editor(this.multipleSelection[0].section_id,
             this.multipleSelection[0].index,
             this.multipleSelection[0].company_name,
             this.multipleSelection[0].company_num
           )
        }
      },
      //删除弹出框  操作
      confirmOpt(){
          console.log(this.multipleSelection)
        console.log('确认删除操作')
        this.dialogFormVisible2 =false;
        var params='';
        if(this.multipleSelection.length){
          for(var i in this.multipleSelection){
            params+=','+this.multipleSelection[i].section_id
          }
        }else{
          params=this.section_id
        }
        this.axios.delete('/api/v1/system/section/'+`${params}`).then((res)=>{
          if(res.data.code==0){
            this.$alert(res.data.message,'提示')
              if(this.multipleSelection.length){
                console.log(this.multipleSelection)
                for(var k in this.multipleSelection){
                  for(var m in this.tableData3){
                    if(this.multipleSelection[k].section_id==this.tableData3[m].section_id){
                        this.tableData3.splice(m,1)
                    }
                  }
                }
              }else{
                this.tableData3.splice(this.index,1)
              }
          }else{
            this.$alert(res.data.message,'提示')
          }
        }).then((res)=>{
          params=''
        })
          .catch((err)=>{
            this.$alert(err.message,'提示')
        })

      },
      //取消删除操作
      cancelOpt(){
        console.log('取消删除操作')
        this.dialogFormVisible2 =false
      },
      renderHeaderOne (h, {column, $index}) {
        //下拉框内容包裹在一个div里面
        return h('ul',[
          h('el-select',{//el-select实现下拉框
            on:{
              input: (value) => {//随着下拉框的不同，文字框里的内容在边
                this.logLevel = value;
                console.log(this.logLevel);
                this.getcompanyData(this.logLevel)
              },
            },
            props:{
              value:this.logLevel,//文字框的内容取决于这个value，如果value不存在，会报错
            },
          },[
            //下拉框里面填充选项，通过filters遍历map，为每一个选项赋值。
            this.formatData.map(item => {
              return h("el-option", {
                props: {
                  value: item.company_id,
                  label: item.company_num
                }
              })
            })
          ])])
      },
      initData(page){
        this.axios.get('/api/v1/system/section',{
          params:{
            limit:10,
            page:page,
          }
        }).then((res)=>{
          console.log(res.data.data)
          if(res.data.code==0){
            this.tableData3=res.data.data;
            this.total = res.data.pagination.total
            this.pageSize =res.data.pagination.pages
            this.currentPage=res.data.pagination.page
          }
        })
      },
      //初始化树状结构的公司列表
      initCompanyData(){
        this.axios.get('/api/v1/system/comsection?subor=collar').then((res)=>{
          console.log(res.data)
          if(res.data.code==0){
            this.data3=res.data.data;
            this.companyData =res.data.data;
            console.log(this.companyData)
          }else{
            //异常处理
            this.$alert(res.data.message,'提示')
          }
        })
      },
      beforeunloadHandler (e) {
//        alert(123)
      },
//     确认添加部门
      confirmAdd(formName){
        let that =this
//        console.log((this.$refs.tree.getCheckedNodes()[0]).company_id)
          if(this.title=='添加部门'){
            this.$refs[formName].validate((valid) => {
              if (valid) {
                this.axios.post('/api/v1/system/section',
                  {
                    section_name:this.form.section_name,
                    company_id:(this.$refs.tree.getCheckedNodes()[0]).company_id
                  })
                  .then((res)=>{
                    console.log(res)
                    this.i=0;
                    this.dialogFormVisible=false
                    if(res.data.code==0){
                      this.tableData3.unshift({
                        company_num:res.data.data.company_num,
                        company_name:res.data.data.company_name,
                        company_id:res.data.data.company_id,
                        section_name:res.data.data.section_name,
                        section_id:res.data.data.section_id
                      })
                      this.form={}
                      this.$refs.tree.setCheckedNodes([]);
                    }else{
                      this.form={}
                      this.$alert(res.data.message, '提示', {
                        confirmButtonText: '确定'
                      })
                    }
                  })
              }else{
                console.log('error submit!!');
                return false;
              }
            })
          }else if(this.title=='编辑'){
            this.$refs[formName].validate((valid) => {
              if (valid) {
                  console.log( this.currentNodeKey)
                  console.log(this.form)
                this.axios.put('/api/v1/system/section/'+`${this.section_id}`,
                  {
                    section_name:this.form.section_name,
                    company_id:(this.$refs.tree.getCheckedNodes()[0]).company_id,
                    section_id:this.form.section_id
                  })
                  .then((res)=>{
                    console.log(res)
                    this.i=0;
                    this.dialogFormVisible=false
                    if(res.data.code==0){
                        //数组未更新待处理
                      console.log(res.data.data.company_num)
                      let newValue ={
                        company_num:this.company_num,
                        company_name:(this.$refs.tree.getCheckedNodes()[0]).company_name,
                        company_id:(this.$refs.tree.getCheckedNodes()[0]).company_id,
                        section_name:this.form.section_name,
                        section_id:this.form.section_id
                      }
//                      this.$set(this.tableData3,this.index,newValue)
                      this.tableData3.splice(this.index,1,newValue)
                      console.log(this.tableData3)
                      this.form={}
                      this.i=0
                      this.$refs.tree.setCheckedNodes([]);
                    }else{
                      this.form={}
                      this.$alert(res.data.message, '提示', {
                        confirmButtonText: '确定'
                      })
                    }
                  }).then((res)=>{
                  this.section_id=''
                  this.index=''
                  this.company_name=''
                  this.company_num=''
                })
              }else{
                console.log('error submit!!');
                return false;
              }
            })
          }


      },
      cancelAdd(){
        this.dialogFormVisible =false;
      },
      getcompanyData(ID){
        this.axios.get('/api/v1/system/comsection/'+`${ID}`)
          .then((res)=>{
            this.tableData3 =res.data.data;
            console.log(res.data.data)
          })
      }
    },
    mounted(){
        this.initData(this.page);
        this.initCompanyData();
        window.addEventListener('beforeunload', e => this.beforeunloadHandler(e));
        this.logLevel =this.company_Item

    },
    destroyed() {
      window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e))
    }
  })
</script>
<style scoped="">
  .departManaIndex{
    width: 100%;
    height: 100%;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    padding: 10px;
  }
  .departManaIndex .el-table  >>>  th.is-leaf{
    background: #d3e9bb;
    height:58px;

  }
  .departManaIndex .el-table  >>> thead  th.is-leaf .cell{
    font-size: 14px;
    color: #5d9120;
    font-weight: normal;
  }
  .departManaIndex .el-table  >>> thead  th.is-leaf .cell .el-select{
    width: 100%;
  }
  .departManaIndex .el-table  >>> thead  th.is-leaf .cell .el-select .el-input--suffix .el-input__inner{
    padding: 0;
    text-align: center;
    border: none;
    background-color: #d3e9bb;
    height: auto;
    line-height: 1;
    color: #5d9120;
  }
  .departManaIndex .el-table  >>> thead  th.is-leaf .cell .el-input{

  }
  .departManaIndex .el-table  >>> thead  th.is-leaf .cell .el-input .el-input__suffix{
    display: inline-block;
    width:17px;
    height: 15px;
    background: #afd682;
    top:50%;
    margin-top: -7px;
  }

  .departManaIndex .el-table  >>> thead  .cell  .el-select .el-input .el-select__caret{
    color: white;
    position: absolute;
    left: 0;
    top: 50%;
    width: 100%;
    text-align: center;
    margin-top: 4px;
    font-size: 12px;
  }
  .departManaIndex .el-table  >>> thead  .cell .el-select .el-input .el-select__caret.is-reverse{
    transform: none;
    -webkit-transform: none;
    top:0;
    margin-top: -12px;
  }

  .departManaIndex .el-table  >>> thead  th.is-leaf .cell .companyNo{
    display: inline-block;
    width: 100%;
    position: relative;
  }
  .departManaIndex  .el-table  >>> tr  th.is-leaf{
    border-bottom: 1px solid #aac983;
    border-right: 1px solid #aac983;
  }
  .departManaIndex  .el-table  >>> .el-table__body-wrapper{
  }
  .departManaIndex  .el-table  >>> .el-table__body-wrapper  .el-table__body  .el-table__row{
    height: 50px !important;
  }
  .departManaIndex .el-table >>> .el-table__body-wrapper   .el-table__body  .el-table__row td{
    height: 50px;
    /*border-bottom: 1px solid #aac983;*/
    border-right: 1px solid #aac983;
  }
  .departManaIndex .el-table >>> .el-table__body-wrapper   .el-table__body tr{
    border-bottom: 1px solid #aac983;
  }
  .departManaIndex .el-table  >>> .el-table__body-wrapper  .el-table__body  .el-table__row .cell{
    text-align: center;
  }

  .departManaIndex  .el-table  >>>  .el-table__header .has-gutter th{
    text-align: center;
  }
  .departManaIndex  .el-table >>>  span.e-ditor{
    margin-right:24px ;
    color: #4577bf;
    text-decoration: underline;
  }
  .departManaIndex  .el-table >>>  span.d-elete{
    color: #4577bf;
    text-decoration: underline;
  }
  .departManaIndex  .e-table-footer{
    background: #d3e9bb;
    height: 50px;
    line-height: 50px;
    border-bottom: 1px solid #aac983;
    border: 1px solid #aac983;
    border-top: 0;
  }
  .departManaIndex  .e-table-footer  .e-selectAll{
    width: 70px;
    text-align: center;
    border-right: 1px solid #aac983;
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    display: inline-block;
  }
  .departManaIndex  .e-table-footer .e-selectText{
    display: inline-block;
    margin-left: 20px;
    color: #5d9120;
  }
  .departManaIndex .e-selectText .e-del{
      font-size: 16px;
      color: #fff;
      padding: 6px 20px;
    background: #f56c6c;
    border-radius:2px ;
    -webkit-border-radius: 2px;
    margin-left: 30px;

  }
  .departManaIndex .el-table >>> .has-gutter .addIcon{
    margin-top: 3px;
    display: inline-block;
      width:17px;
      height: 15px;
       background: #afd682;
      margin-left: 6px;
    border-radius: 2px;
    -webkit-border-radius: 2px;
    background-image: url("../../static/images/icon-down.png");
    background-repeat: no-repeat;
    background-position: center;
  }
  .departManaIndex  >>> .el-dialog{
   width: 760px;
 }
  .departManaIndex >>> .el-button--primary{
    background: #8bc34a;
    border-color: #8bc34a;
  }
  .departManaIndex >>> .el-form-item__content{
    width: 380px;
  }

  .departManaIndex >>> .el-dialog .el-form .el-form-item{
    margin-bottom: 24px;
  }
  .departManaIndex >>> .has-gutter .cell .el-checkbox__inner{
    display: none;
  }
  .departManaIndex .companyNo{

  }
  .departManaIndex >>> .companyNo ul{
    position: absolute;
    background: red;
    width: 100%;
    height: auto;
    left: 0;
    top:0;
  }
  .departManaIndex >>> .companyNo ul li{
    text-align: center;
    width: 100%;
    display: block;
    color: #ccc;
    height: 24px;
  }
  @media screen and (max-width: 1400px){
    .departManaIndex{
      padding: 6px;
    }
  }
</style>
